﻿using ModuleLauncher.Re.Authenticators;
using ModuleLauncher.Re.Launcher;
using ModuleLauncher.Re.Locators.Concretes;
using ModuleLauncher.Re.Models.Authenticators;
using Panuon.UI.Core;
using Panuon.UI.Silver;

using ProjBobcat.Class.Helper;
using ProjBobcat.Class.Model;
using ProjBobcat.Class.Model.LauncherProfile;
using ProjBobcat.DefaultComponent.Authenticator;
using ProjBobcat.DefaultComponent.Launch;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
using WaveringLand_Launcher.Helper;
using WaveringLand_Launcher.Helper.Net;
using WaveringLand_Launcher.Model;
using WaveringLand_Launcher.View;

namespace WaveringLand_Launcher.ViewModel
{
    [PropertyChanged.AddINotifyPropertyChangedInterface]
    public class LaunchViewModel
    {
        public bool isLaunching { get; set; }

        public bool Waiting { get; set; }
        public string Output { get; set; }

        public ICommand CheckResourcesBtnClickCommand { get; set; }
        public ICommand SettingBtnClickCommand { get; set; }
        public ICommand LaunchBtnClickCommand { get; set; }
        public ICommand LabelClickCommand { get; set; }

        public LaunchViewModel()
        {
            CheckResourcesBtnClickCommand = new RelayCommand(CheckResourcesBtnClick);
            SettingBtnClickCommand = new RelayCommand(SettingBtnClick);
            LaunchBtnClickCommand = new RelayCommand(LaunchBtnClick);
            LabelClickCommand = new RelayCommand(LabelClick);
        }


        async Task<bool> CheckMustLack()
        {
            var lackfiles = await ResHelper.GetLackMustFiles();

            if (lackfiles is { Count: 0 } or null)
            {
                return true;
            }
            else
            {
                App.ShowMessage("有部分服务器必须资源文件缺失，请在更新资源页面下载。");
                return false;
            }


        }

        /// <summary>
        /// 检查配置文件以及弹出提示
        /// </summary>
        /// <param name="config"></param>
        /// <returns></returns>
        bool CheckConfig(WllConfig config)
        {

            if (config.JavaPath == "")
            {
                MessageBoxX.Show("Java路径为空,请在设置界面中更改。");
                return false;
            }

            if (config.Accounts is null or { Count: 0 })
            {
                MessageBoxX.Show("账户列表为空，请在设置中增加并选中使用的账户");
                return false;

            }
            WAccount account = config.Accounts[config.SelectedAccount];

            if (account.Account == "")
            {
                MessageBoxX.Show("用户Account配置出错,请在设置界面中更改。");
                return false;

            }


            return true;
        }

        //在做了
        public void LauncheGame()
        {
        }

        void CheckResourcesBtnClick(object sender)
        {

            App.SetView(new GameResourcesView());
        }

        void SettingBtnClick(object sender)
        {
            App.SetView(new SettingView());
        }

        async void LaunchBtnClick(object sender)
        {

            //check Version
            if (VersionHelper.CheckNeedUpdate())
            {
                App.ShowMessage("需要下载新版启动器~");
                VersionHelper.OpenLauncherDownPage();
                return;
            }
            //LauncheGame();
            var cfg = ConfigurationHelper.GetConfig();
            if (await CheckMustLack() && CheckConfig(cfg))
            {
                Launch2();
            }
        }

        void LabelClick(object sender)
        {
            TipHelper.ShowRandomTipWindow();
        }

        async void Launch2()
        {

            isLaunching = true;

            var config = ConfigurationHelper.GetConfig();
            var account = config.Accounts[config.SelectedAccount];


            AuthenticatorBase authenticator = account.AccountType switch
            {

                AccountType.Offline =>
                new ModuleLauncher.Re.Authenticators.OfflineAuthenticator
                {
                    Account = account.Account
                },
                AccountType.Mojang => new ModuleLauncher.Re.Authenticators.MojangAuthenticator
                {
                    Account = account.Account,
                    Password = account.Password
                },
                AccountType.Microsoft => new ModuleLauncher.Re.Authenticators.MicrosoftAuthenticator
                {
                    Code = account.ExtraCode,
                },
                _ => throw new System.NotImplementedException()
            };

            MinecraftLocator locator = new(Directory.GetCurrentDirectory() + "\\.minecraft");

            AuthenticateResult authresult = null;
            try
            {
                if (account.AccountType is AccountType.Microsoft)
                {
                    Debug.WriteLine(account.Password);

                    var result = await HeerDev.MLRExtension.Authenticator.MicrosoftLogger.Login(account.Password);
                    Debug.WriteLine(result.RefreshAccessToken);

                    ConfigurationHelper.UpdateRefreshToken(account.Password, result.RefreshAccessToken);

                    authresult = new() { AccessToken = result.AccessToken, Name = result.Name, Uuid = result.UUID };
                }
                else
                {

                    authresult = await authenticator.Authenticate();

                }
            }
            catch (Exception ex)
            {
                App.ShowMessage("尝试登入账户失败~" + ex.Message);
                isLaunching = false;
                return;

            }


            var launchercore = new Launcher(locator)
            {
                Java = config.JavaPath,
                MaximumMemorySize = config.MaxMemory,
                Authentication = authresult
            };

            if ((await locator.GetLocalMinecrafts())?.ToList() is null or { Count: 0 })
            {
                //找不到游戏
                App.ShowMessage("似乎目前并没有任何游戏版本(请问整合包是否正确!\n或者请去下载正确的Version文件");
                isLaunching = false;
                return;
            }

            var id = (await locator.GetLocalMinecrafts()).ToList()[0].Raw.Id;

            try
            {
                var process = await launchercore.Launch(id);
                process.BeginOutputReadLine();
                process.OutputDataReceived += delegate (object sender, DataReceivedEventArgs e)
                {
                    Output = (string)e.Data;
                };
                process.Exited += delegate (object sender, EventArgs e)
                  {
                      isLaunching = false;

                  };
                //rocess.WaitForExit();
            }
            catch (Exception ex)
            {
                App.ShowMessage("启动中出现了异常~!" + ex.Message);
                isLaunching = false;

            }

        }


    }
}